<style type="text/css">
    .layui-upload-drag {
        position: relative;
        padding: 10px;
        border: 1px dashed #e2e2e2;
        background-color: #fff;
        text-align: center;
        cursor: pointer;
        color: #999;
        margin-right:10px;
        margin-bottom:10px;
    }
    .del_img{
        position: absolute;
        z-index: 99;
        right: 0;
        top: 0;
        width: 25px;
        height: 25px;
        display: block;
    }
    .del_img img{
        position: absolute;
        z-index: 9;
        right: 0px;
        top: 0px;
        width: 25px;
        height: 25px;
        display: inline-block;
    }
</style>

{if $imageList neq null}
{volist name="imageList" id="row"}
<div class="layui-upload-drag">
    <div class="del_img" {if $show_del} style="display:none;"{/if} onclick="removeImage_{$name}(this);">
        <img src="{__SGADMIN_PATH}images/delete.png">
    </div>
    <a href="{$row}" target="_blank">
        <img name="imageSrc_{$name}" src="{$row}" alt="{$imgMsg}(点击放大预览)" title="{$imgMsg}(点击放大预览)" width="{$imgW}" height="{$imgH}">
    </a>
</div>
{/volist}
{/if}
<div class="layui-upload-drag imgUp_{$name}" {if (!empty($imageList) && count($imageList)==$maxNum) || $show_del}style="display:none;"{/if}>
    <img id="btnUploadImg_{$name}" src="{__SGHOME_PATH}images/icon3.png" alt="上传{$imgMsg}" title="上传{$imgMsg}" width="{$imgW}" height="{$imgH}">
    <input type="hidden" id="{$name}" name="{$name}" value="" >
</div>

<script type="text/javascript">
    layui.use(['upload'],function(){
        // 声明变量
        var upload = layui.upload
            ,$ = layui.$;

        // 初始化图片隐藏域
        var ids = '';
        $('img[name="imageSrc_{$name}"]').each(function(){
            ids += $(this).attr('src') + ","
        });
        ids = ids.substr(0, (ids.length - 1));
        $("#{$name}").val(ids);

        var hideStr = $("#{$name}").attr("value");
        var itemArr = hideStr.split(',');
        if(itemArr.length>={$maxNum}){
            $(".imgUp_{$name}").hide();
        }

        /**
         * 普通图片上传
         */
        var uploadInst = upload.render({
            elem: '#btnUploadImg_{$name}'
            ,url: "{:url('homecommon/UpImages')}" //头像上传地址
            ,accept:'images'
            ,acceptMime:'image/*'
            ,exts: "{$uploadImgExt}"
            ,size: {$uploadImgSize} //最大允许上传的文件大小
            ,multiple: true
            ,number: {$uploadImgMax} //最大上传张数,
            ,auto: false,
            choose: function (obj) { //选择文件后的回调
                var files = obj.pushFile();
                var filesArry = [];
                for (var key in files) { //将上传的文件转为数组形式
                    filesArry.push(files[key])
                }
                var index = filesArry.length - 1;
                var file = filesArry[index]; //获取最后选择的图片,即处理多选情况

                if (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion.split(";")[1]
                    .replace(/[ ]/g, "").replace("MSIE", "")) < 9) {
                    return obj.upload(index, file)
                }
                canvasDataURL(file, function (blob) {
                    var aafile = new File([blob], file.name, {
                        type: file.type
                    })
                    var isLt1M;
                    if (file.size < aafile.size) {
                        isLt1M = file.size
                    } else {
                        isLt1M = aafile.size
                    }

                    if (isLt1M / 1024 / 1024 > 100000000) {
                        return layer.alert('上传图片过大！')
                    } else {
                        if (file.size < aafile.size) {
                            return obj.upload(index, file)
                        }
                        obj.upload(index, aafile)
                    }
                })
            },
            done: function (res) {
                //上传完毕回调

                hideStr = $("#{$name}").attr("value");
                itemArr = hideStr.split(',');
                if(itemArr.length>={$maxNum}){
                    layer.msg("最多上传{$maxNum}张图片",{ icon: 5,time: 1000}, function () {
                        //TODO...
                        $(".imgUp_{$name}").hide();
                    });
                    return false;
                }

                //如果上传失败
                if(res.code = 0){
                    return layer.msg('上传失败');
                }

                //渲染界面
                var attStr = '<div class="layui-upload-drag">'+
                    '<div class="del_img" onclick="removeImage_{$name}(this);">'+
                    '<img src="{__SGADMIN_PATH}images/delete.png"></img>'+
                    '</div>'+
                    '<a href="'+res.path+'" target="_blank">'+
                    '<img name="imageSrc_{$name}" src="'+res.path+'" alt="{$imgMsg}(点击放大预览)" title="{$imgMsg}(点击放大预览)" width="{$imgW}" height="{$imgH}">'+
                    '</a>'+
                    '</div>';
                $(".imgUp_{$name}").before(attStr);

                //获取最新的图集
                var ids = '';
                $('img[name="imageSrc_{$name}"]').each(function(){
                    ids += $(this).attr('src') + ","
                });
                ids = ids.substr(0, (ids.length - 1));
                //给隐藏域赋值
                $("#{$name}").val(ids);

                hideStr = $("#{$name}").attr("value");
                itemArr = hideStr.split(',');
                if(itemArr.length>={$maxNum}){
                    $(".imgUp_{$name}").hide();
                }
                // console.log(itemArr.length);

                return false;
            },
            error: function () {
                //请求异常回调
                return layer.msg('数据请求异常');
            }
        });

    });

    function canvasDataURL(file, callback) { //压缩转化为base64
        var reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = function (e) {
            var base64 = null;
            //图片方向角 added by lzk
            var Orientation = null;
            const img = new Image()
            const quality = 0.8 // 图像质量
            const canvas = document.createElement('canvas')
            const drawer = canvas.getContext('2d')
            img.src = this.result
            img.onload = function () {
                var expectWidth = this.naturalWidth;
                var expectHeight = this.naturalHeight;
                if (this.naturalWidth > this.naturalHeight && this.naturalWidth > 800) {
                    expectWidth = 800;
                    expectHeight = expectWidth * this.naturalHeight / this.naturalWidth;
                } else if (this.naturalHeight > this.naturalWidth && this.naturalHeight > 1200) {
                    expectHeight = 1200;
                    expectWidth = expectHeight * this.naturalWidth / this.naturalHeight;
                }
                // console.log(expectWidth,expectHeight,img.width,img.height)
                // canvas.width = img.width
                // canvas.height = img.height
                canvas.width = expectWidth;
                canvas.height = expectHeight;
                drawer.drawImage(this, 0, 0, expectWidth, expectHeight);
                //修复ios
                if (navigator.userAgent.match(/iphone/i)) {
                    console.log('iphone');
                    //alert(expectWidth + ',' + expectHeight);
                    //如果方向角不为1，都需要进行旋转 added by lzk
                    if(Orientation != "" && Orientation != 1){
                        switch(Orientation){
                            case 6://需要顺时针（向左）90度旋转
                                rotateImg(this,'left',canvas);
                                break;
                            case 8://需要逆时针（向右）90度旋转
                                rotateImg(this,'right',canvas);
                                break;
                            case 3://需要180度旋转
                                rotateImg(this,'upside',canvas);
                                break;
                        }
                    }
                    base64 = canvas.toDataURL(file.type, quality);
                }
                else if(navigator.userAgent.match(/Android/i)) {
                    //var encoder = new JPEGEncoder();
                    //base64 = encoder.encode(ctx.getImageData(0, 0, expectWidth, expectHeight), 80);
                    base64 = canvas.toDataURL(file.type, quality);
                }
                else{
                    alert(Orientation);
                    if(Orientation != "" && Orientation != 1){
                        //alert('旋转处理');
                        switch(Orientation){
                            case 6://需要顺时针（向左）90度旋转
                                rotateImg(this,'left',canvas);
                                break;
                            case 8://需要逆时针（向右）90度旋转
                                rotateImg(this,'right',canvas);
                                break;
                            case 3://需要180度旋转
                                rotateImg(this,'upside',canvas);
                                break;
                        }
                    }

                    base64 = canvas.toDataURL(file.type, quality);
                }
                console.log('////11');
                convertBase64UrlToBlob(base64, callback);
            }
        }
    }

    function convertBase64UrlToBlob(urlData, callback) { //将base64转化为文件格式
        const arr = urlData.split(',')
        const mime = arr[0].match(/:(.*?);/)[1]
        const bstr = atob(arr[1])
        let n = bstr.length
        const u8arr = new Uint8Array(n)
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
        }
        callback(new Blob([u8arr], {
            type: mime
        }));
    }

    // 删除图片
    function removeImage_{$name}(obj) {
        //obj.remove();
        layui.$(obj).parent().remove();

        //获取最新的图集
        var ids = '';
        layui.$('img[name="imageSrc_{$name}"]').each(function(){
            ids += layui.$(this).attr('src') + ","
        });
        ids = ids.substr(0, (ids.length - 1));
        //给隐藏域赋值
        layui.$("#{$name}").val(ids);

        $(".imgUp_{$name}").show();
    }

</script>